package com.api.controller;


import com.api.annotation.Login;
import com.api.common.constant.Constant;
import com.api.common.exception.MySystemException;
import com.api.common.utils.Result;
import com.api.entity.Comment;
import com.api.entity.StarCollect;
import com.api.entity.User;
import com.api.service.CommentService;
import com.api.service.IStarCollectService;
import com.api.service.UploadService;
import com.api.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 评论表 前端控制器
 * </p>
 *
 * @author author
 * @since 2024-09-30
 */
@RestController
@RequestMapping("/api/comment")
@AllArgsConstructor
public class CommentController {

    private final UserService userService;
    private  final CommentService commentService;

    @Autowired
    private UploadService uploadService;
    @Login
    @GetMapping("{id}")
    @Operation(summary = "评论列表")
    public Result getCollect(@PathVariable("id") Long id) {
        LambdaQueryWrapper<Comment> lwq = new LambdaQueryWrapper<>();
        lwq.eq(Comment::getItemId,id);
        lwq.orderByDesc(Comment::getCreateTime);
        List<Comment> list = commentService.list(lwq);

        ArrayList<Comment> res = new ArrayList<>();
        for (Comment comment : list) {
            Comment comment1 = new Comment();
            User user = userService.selectById(comment.getUserId());
            if (user != null) {
                BeanUtils.copyProperties(comment,comment1);
                comment1.setUserName(user.getUserName());
            }else {
                comment1.setUserName("无上的平凡用户！");
            }
            res.add(comment1);
        }

        return new Result().ok(res);
    }


    @Login
    @PostMapping
    @Operation(summary = "添加评论")
    public Result save(@RequestBody Comment comment,
                       @Parameter(hidden = true) @RequestAttribute("userId") Long userId) {
        comment.setUserId(userId);
        commentService.save(comment);
        return new Result();
    }


}
